<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/favicon.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon.png">
  <link rel="mask-icon" href="/images/favicon.png" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/gh/fancyapps/fancybox@3/dist/jquery.fancybox.min.css">


<script id="hexo-configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    hostname: new URL('https://codz-me.vercel.app').hostname,
    root: '/',
    scheme: 'Muse',
    version: '7.7.1',
    exturl: false,
    sidebar: {"position":"right","display":"post","padding":18,"offset":12,"onmobile":false},
    copycode: {"enable":false,"show_result":false,"style":null},
    back2top: {"enable":true,"sidebar":false,"scrollpercent":false},
    bookmark: {"enable":false,"color":"#222","save":"auto"},
    fancybox: true,
    mediumzoom: false,
    lazyload: false,
    pangu: false,
    comments: {"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},
    algolia: {
      appID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    },
    localsearch: {"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},
    path: '',
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}
  };
</script>

  <meta name="description" content="Remark: Finished read 1-7, 2015-07-23 15:40:57Multithreading in Java is a very important topic. I have written a lot about Threads in Java. Java Thread is a lightweight process that executes some task">
<meta property="og:type" content="article">
<meta property="og:title" content="[Repost]Multithreading in Java">
<meta property="og:url" content="https://codz-me.vercel.app/2015/07/23/multithreading-in-java/index.html">
<meta property="og:site_name" content="Code Is Poetry">
<meta property="og:description" content="Remark: Finished read 1-7, 2015-07-23 15:40:57Multithreading in Java is a very important topic. I have written a lot about Threads in Java. Java Thread is a lightweight process that executes some task">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://codz-me.vercel.app/2015/07/23/multithreading-in-java/multithreading-in-java.jpg">
<meta property="og:image" content="https://codz-me.vercel.app/2015/07/23/multithreading-in-java/java-thread.png">
<meta property="article:published_time" content="2015-07-22T17:30:00.000Z">
<meta property="article:modified_time" content="2015-07-23T07:40:57.000Z">
<meta property="article:author" content="laudukang">
<meta property="article:tag" content="java">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://codz-me.vercel.app/2015/07/23/multithreading-in-java/multithreading-in-java.jpg">

<link rel="canonical" href="https://codz-me.vercel.app/2015/07/23/multithreading-in-java/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome: false,
    isPost: true
  };
</script>

  <title>[Repost]Multithreading in Java | Code Is Poetry</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-meta">

    <div>
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Code Is Poetry</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
  </div>

  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-fw fa-user"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-fw fa-th"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档</a>

  </li>
        <li class="menu-item menu-item-commonweal">

    <a href="/404/" rel="section"><i class="fa fa-fw fa-heartbeat"></i>公益 404</a>

  </li>
  </ul>

</nav>
</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content">
            

  <div class="posts-expand">
      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block " lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://codz-me.vercel.app/2015/07/23/multithreading-in-java/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/head.png">
      <meta itemprop="name" content="laudukang">
      <meta itemprop="description" content="Bug Not Found">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Code Is Poetry">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          [Repost]Multithreading in Java
        </h1>

        <div class="post-meta">
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2015-07-23 15:40:57 15:40:57" itemprop="dateModified" datetime="2015-07-23T15:40:57+08:00">2015-07-23 15:40:57</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Java/" itemprop="url" rel="index">
                    <span itemprop="name">Java</span>
                  </a>
                </span>
            </span>

          
            <span id="/2015/07/23/multithreading-in-java/" class="post-meta-item leancloud_visitors" data-flag-title="[Repost]Multithreading in Java" title="阅读次数">
                <span hidden class="leancloud-visitors-count"></span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h4 id="Remark-Finished-read-1-7-2015-07-23-15-40-57"><a href="#Remark-Finished-read-1-7-2015-07-23-15-40-57" class="headerlink" title="Remark: Finished read 1-7, 2015-07-23 15:40:57"></a>Remark: Finished read 1-7, 2015-07-23 15:40:57</h4><p>Multithreading in Java is a very important topic. I have written a lot about Threads in Java. Java Thread is a lightweight process that executes some task. Java provides multithreading support with the Thread class and an application can create multiple threads executing concurrently.</p>
<img src="/2015/07/23/multithreading-in-java/multithreading-in-java.jpg" alt="multithreading-in-java.jpg" title="">


<p>There are two types of threads in an application – user thread and daemon thread. When we start an application, main is the first user thread created and we can create multiple user threads as well as daemon threads. When all the user threads are executed, JVM terminates the program.</p>
<p>We can set different priorities to different Threads but it doesn’t guarantee that higher priority thread will execute first than lower priority thread. Thread scheduler is the part of Operating System implementation and when a Thread is started, it’s execution is controlled by Thread Scheduler and JVM doesn’t have any control on it’s execution.</p>
<p>We can create Threads by either implementing Runnable interface or by extending Thread Class.</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">Thread t = <span class="keyword">new</span> Thread(<span class="keyword">new</span> Runnable()&#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>Above is a one liner statement to create new Thread, Here we are creating Runnable as Anonymous Class, read this post to learn about inner class, nested class and anonymous inner class.</p>
<p>In last few weeks, I have posted some useful articles on multithreading in java, you can follow them in order to learn about Threads in Java.</p>
<h1 id="Threads-in-Java"><a href="#Threads-in-Java" class="headerlink" title="Threads in Java"></a>Threads in Java</h1><img src="/2015/07/23/multithreading-in-java/java-thread.png" alt="java-thread.png" title="">


<p>With Java 8 lambda expressions, we can create Thread in java like below too because Runnable is a functional interface.</p>
<ol>
<li><h3 id="Java-Thread-Example"><a href="#Java-Thread-Example" class="headerlink" title="Java Thread Example"></a><span id="java-thread-example"><a href="https://www.journaldev.com/1016/java-thread-example" target="_blank" rel="noopener">Java Thread Example</a></span></h3><p>This is the first post in the multithreading in java tutorial series. Read this to learn about <strong>Process</strong> and <strong>Thread</strong>. What is the difference between Thread and Process. Benefits of using Threads and how we can create Threads using <strong>Runnable</strong> interface and <strong>Thread</strong> class. This post also compares Runnable interface with Thread class.</p>
</li>
<li><h3 id="Java-Thread-Sleep"><a href="#Java-Thread-Sleep" class="headerlink" title="Java Thread Sleep"></a><span id="java-thread-sleep"><a href="https://www.journaldev.com/1020/thread-sleep-java" target="_blank" rel="noopener">Java Thread Sleep</a></span></h3><p><em>Java Thread sleep</em> is used to pause the execution of current thread. We will use Thread sleep extensively in future posts, so it’s good to know how it works and is it accurate or not?</p>
</li>
<li><h3 id="Java-Thread-Join"><a href="#Java-Thread-Join" class="headerlink" title="Java Thread Join"></a><span id="java-thread-join"><a href="https://www.journaldev.com/1024/java-thread-join-example" target="_blank" rel="noopener">Java Thread Join</a></span></h3><p>Sometimes we need to wait for other threads to finish it’s execution before we can proceed. We can achieve this using <strong>Thread join</strong>, learn how it works and when we should use it.</p>
</li>
<li><h3 id="Java-Thread-States"><a href="#Java-Thread-States" class="headerlink" title="Java Thread States"></a><span id="java-thread-states"><a href="https://www.journaldev.com/1044/thread-life-cycle-in-java-thread-states-in-java" target="_blank" rel="noopener">Java Thread States</a></span></h3><p>Understanding different <strong>states of thread</strong> is important. Learn how thread changes it’s state and how thread scheduler changes thread state.</p>
</li>
<li><h3 id="Java-Thread-wait-notify-and-notifyAll"><a href="#Java-Thread-wait-notify-and-notifyAll" class="headerlink" title="Java Thread wait, notify and notifyAll"></a><span id="java-thread-wait-notify-and-notifyall"><a href="https://www.journaldev.com/1037/java-thread-wait-notify-and-notifyall-example" target="_blank" rel="noopener">Java Thread wait, notify and notifyAll</a></span></h3><p>Java Object class contains three methods using which threads can communicate about the lock status of a resource. Learn with example usage of these Object class methods in a simple Wait-Notify implementation.</p>
</li>
<li><h3 id="Java-Thread-Safety-and-Java-Synchronization"><a href="#Java-Thread-Safety-and-Java-Synchronization" class="headerlink" title="Java Thread Safety and Java Synchronization"></a><span id="java-thread-safety-and-java-synchronization"><a href="https://www.journaldev.com/1061/thread-safety-in-java" target="_blank" rel="noopener" title="Java Synchronization and Thread Safety Tutorial with Examples">Java Thread Safety and Java Synchronization</a></span></h3><p>We know that Threads share Object resources, it can lead to data corruption because these operations are not atomic. Learn how we can achieve <strong><a href="https://www.journaldev.com/1061/thread-safety-in-java" target="_blank" rel="noopener">thread safety in java</a></strong> using different methods. Read this post to learn about the correct usage of <strong>synchronization</strong>, synchronized methods and synchronized blocks.<br>There are various examples of synchronized usage and the post explains what are the issues with them.</p>
</li>
<li><h3 id="Java-Exception-in-thread-main"><a href="#Java-Exception-in-thread-main" class="headerlink" title="Java Exception in thread main"></a><span id="java-exception-in-thread-main"><a href="https://www.journaldev.com/611/exception-in-thread-main-java" target="_blank" rel="noopener">Java Exception in thread main</a></span></h3><p>JVM creates first thread using <strong>main</strong> method. This post explains about some common exceptions we see in daily life and what is the root cause of them and how to fix them.</p>
</li>
<li><h3 id="Thread-Safety-in-Singleton-Class"><a href="#Thread-Safety-in-Singleton-Class" class="headerlink" title="Thread Safety in Singleton Class"></a><span id="thread-safety-in-singleton-class"><a href="https://www.journaldev.com/171/thread-safety-in-java-singleton-classes-with-example-code" target="_blank" rel="noopener">Thread Safety in Singleton Class</a></span></h3><p>In this article, you will learn basic concepts of creating Singleton class. What are thread safety issues with different implementation. How we can achieve <strong>thread safety in Singleton class</strong>.</p>
</li>
<li><h3 id="Daemon-Thread-in-Java"><a href="#Daemon-Thread-in-Java" class="headerlink" title="Daemon Thread in Java"></a><span id="daemon-thread-in-java"><a href="https://www.journaldev.com/1072/daemon-thread-in-java" target="_blank" rel="noopener" title="Daemon Thread in Java">Daemon Thread in Java</a></span></h3><p>A simple article explaining about <strong>daemon threads</strong> and how we can create daemon threads in java.</p>
</li>
<li><h3 id="Java-Thread-Local"><a href="#Java-Thread-Local" class="headerlink" title="Java Thread Local"></a><span id="java-thread-local"><a href="https://www.journaldev.com/1076/java-threadlocal-example" target="_blank" rel="noopener" title="Java ThreadLocal Example to create thread-local variables">Java Thread Local</a></span></h3><p>We know that threads share Object’s variables but what if we want to have thread-local variables created at class level. Java provides <strong>ThreadLocal</strong> utility class to create thread-local variables. Read more to learn about how we can create <em>ThreadLocal</em> variables in java program.</p>
</li>
<li><h3 id="Java-Thread-Dump"><a href="#Java-Thread-Dump" class="headerlink" title="Java Thread Dump"></a><span id="java-thread-dump"><a href="https://www.journaldev.com/1053/java-thread-dump-visualvm-jstack-kill-3-jcmd" target="_blank" rel="noopener" title="How to generate Thread Dump in Java">Java Thread Dump</a></span></h3><p><strong>Java Thread dump</strong> provides the current threads information for the program. Java Thread dump provides useful information to analyze performance issues with the application. You can use thread dump to find and fix deadlock situations. This post explains different methods that can be used to generate thread dump in java.</p>
</li>
<li><h3 id="How-to-Analyze-Deadlock-and-avoid-it-in-Java"><a href="#How-to-Analyze-Deadlock-and-avoid-it-in-Java" class="headerlink" title="How to Analyze Deadlock and avoid it in Java"></a><span id="how-to-analyze-deadlock-and-avoid-it-in-java"><a href="https://www.journaldev.com/1058/deadlock-in-java-example" target="_blank" rel="noopener" title="Java Deadlock Example and How to analyze deadlock situation">How to Analyze Deadlock and avoid it in Java</a></span></h3><p>Deadlock is a situation where multiple threads are waiting for each other to release resources causing cyclic dependency. This article discusses about the situation in which we can get deadlock in a java program. How we can use Thread dump to find the deadlock and best practices to <strong>avoid deadlock in java</strong> program.</p>
</li>
<li><h3 id="Java-Timer-Thread"><a href="#Java-Timer-Thread" class="headerlink" title="Java Timer Thread"></a><span id="java-timer-thread"><a href="https://www.journaldev.com/1050/java-timer-timertask-example" target="_blank" rel="noopener" title="Java Timer TimerTask Example">Java Timer Thread</a></span></h3><p>This post explains how we can use <strong>Java Timer</strong> and TimerTask classes to create jobs to run at scheduled interval, an example program showing it’s usage and how we can cancel the timer.</p>
</li>
<li><h3 id="Java-Producer-Consumer-Problem"><a href="#Java-Producer-Consumer-Problem" class="headerlink" title="Java Producer Consumer Problem"></a><span id="java-producer-consumer-problem"><a href="https://www.journaldev.com/1034/java-blockingqueue-example" target="_blank" rel="noopener" title="Java BlockingQueue Example implementing Producer Consumer Problem">Java Producer Consumer Problem</a></span></h3><p>Before Java 5, producer-consumer problem can be solved using wait() and notify() methods but introduction of BlockingQueue has made it very easy. Learn how we can use BlockingQueue to solve producer consumer problem in java.</p>
</li>
<li><h3 id="Java-Thread-Pool"><a href="#Java-Thread-Pool" class="headerlink" title="Java Thread Pool"></a><span id="java-thread-pool"><a href="https://www.journaldev.com/1069/threadpoolexecutor-java-thread-pool-example-executorservice" target="_blank" rel="noopener" title="Java Thread Pool Example using Executors and ThreadPoolExecutor">Java Thread Pool</a></span></h3><p>Java Thread Pool is a collection of worker threads waiting to process jobs. Java 5 introduction of Executor framework has made it very easy to create thread pool in java using Executors and ThreadPoolExecutor classes. Learn how to use them to create thread pool in java.</p>
</li>
<li><h3 id="Java-Callable-Future"><a href="#Java-Callable-Future" class="headerlink" title="Java Callable Future"></a><span id="java-callable-future"><a href="https://www.journaldev.com/1090/java-callable-future-example" target="_blank" rel="noopener" title="Java Callable Future Example">Java Callable Future</a></span></h3><p>Sometimes we wish Thread could return values that we can use. Java 5 Callable can be used in that case that is similar as Runnable interface. We can use Executor framework to execute Callable tasks.</p>
</li>
<li><h3 id="Java-FutureTask-Example"><a href="#Java-FutureTask-Example" class="headerlink" title="Java FutureTask Example"></a><span id="java-futuretask-example"><a href="https://www.journaldev.com/1650/java-futuretask-example-program" target="_blank" rel="noopener" title="Java FutureTask Example">Java FutureTask Example</a></span></h3><p>FutureTask class is the base concrete class that implements Future interface. We use it with Callable implementation and Executors for asynchronous processing. FutureTask provide implementation methods to check the state of the task and return the value to the calling program once it’s processing is finished. It comes handy when you want to override some of the implementation methods of the Future interface.</p>
</li>
</ol>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/java/" rel="tag"># java</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2015/07/20/java-post-validation-code/" rel="prev" title="Java 实现图形验证码">
      <i class="fa fa-chevron-left"></i> Java 实现图形验证码
    </a></div>
      <div class="post-nav-item">
    <a href="/2015/07/27/music-piao-yao-zhou-xun/" rel="next" title="飘摇-周迅.mp3">
      飘摇-周迅.mp3 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  

  </div>


          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let activeClass = CONFIG.comments.activeClass;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-4"><a class="nav-link" href="#Remark-Finished-read-1-7-2015-07-23-15-40-57"><span class="nav-number">1.</span> <span class="nav-text">Remark: Finished read 1-7, 2015-07-23 15:40:57</span></a></li></ol></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Threads-in-Java"><span class="nav-number"></span> <span class="nav-text">Threads in Java</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Java-Thread-Example"><span class="nav-number"></span> <span class="nav-text">Java Thread Example</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Java-Thread-Sleep"><span class="nav-number"></span> <span class="nav-text">Java Thread Sleep</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Java-Thread-Join"><span class="nav-number"></span> <span class="nav-text">Java Thread Join</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Java-Thread-States"><span class="nav-number"></span> <span class="nav-text">Java Thread States</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Java-Thread-wait-notify-and-notifyAll"><span class="nav-number"></span> <span class="nav-text">Java Thread wait, notify and notifyAll</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Java-Thread-Safety-and-Java-Synchronization"><span class="nav-number"></span> <span class="nav-text">Java Thread Safety and Java Synchronization</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Java-Exception-in-thread-main"><span class="nav-number"></span> <span class="nav-text">Java Exception in thread main</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Thread-Safety-in-Singleton-Class"><span class="nav-number"></span> <span class="nav-text">Thread Safety in Singleton Class</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Daemon-Thread-in-Java"><span class="nav-number"></span> <span class="nav-text">Daemon Thread in Java</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Java-Thread-Local"><span class="nav-number"></span> <span class="nav-text">Java Thread Local</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Java-Thread-Dump"><span class="nav-number"></span> <span class="nav-text">Java Thread Dump</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#How-to-Analyze-Deadlock-and-avoid-it-in-Java"><span class="nav-number"></span> <span class="nav-text">How to Analyze Deadlock and avoid it in Java</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Java-Timer-Thread"><span class="nav-number"></span> <span class="nav-text">Java Timer Thread</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Java-Producer-Consumer-Problem"><span class="nav-number"></span> <span class="nav-text">Java Producer Consumer Problem</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Java-Thread-Pool"><span class="nav-number"></span> <span class="nav-text">Java Thread Pool</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Java-Callable-Future"><span class="nav-number"></span> <span class="nav-text">Java Callable Future</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Java-FutureTask-Example"><span class="nav-number"></span> <span class="nav-text">Java FutureTask Example</span></a></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="laudukang"
      src="/images/head.png">
  <p class="site-author-name" itemprop="name">laudukang</p>
  <div class="site-description" itemprop="description">Bug Not Found</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">68</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">10</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">25</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/laudukang" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;laudukang" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://gitee.com/laudukang" title="Gitee → https:&#x2F;&#x2F;gitee.com&#x2F;laudukang" rel="noopener" target="_blank"><i class="fa fa-fw fa-github-alt"></i>Gitee</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://stackoverflow.com/users/5621049/laudukang" title="StackOverflow → https:&#x2F;&#x2F;stackoverflow.com&#x2F;users&#x2F;5621049&#x2F;laudukang" rel="noopener" target="_blank"><i class="fa fa-fw fa-stack-overflow"></i>StackOverflow</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://www.google.com/maps/place/%E6%B7%B1%E5%9C%B3%E5%B8%82%E8%BD%AF%E4%BB%B6%E4%BA%A7%E4%B8%9A%E5%9F%BA%E5%9C%B0/@22.5244896,113.9382973,17z/data=!3m1!4b1!4m5!3m4!1s0x3403ee17d008a019:0xbb7b06b73d856c14!8m2!3d22.5244896!4d113.9382973" title="Map → https:&#x2F;&#x2F;www.google.com&#x2F;maps&#x2F;place&#x2F;%E6%B7%B1%E5%9C%B3%E5%B8%82%E8%BD%AF%E4%BB%B6%E4%BA%A7%E4%B8%9A%E5%9F%BA%E5%9C%B0&#x2F;@22.5244896,113.9382973,17z&#x2F;data&#x3D;!3m1!4b1!4m5!3m4!1s0x3403ee17d008a019:0xbb7b06b73d856c14!8m2!3d22.5244896!4d113.9382973" rel="noopener" target="_blank"><i class="fa fa-fw fa-map-marker"></i>Map</a>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

<div class="copyright">
  
  &copy; 2015 – 
  <span itemprop="copyrightYear">2025</span>
  <span class="with-love">
    <i class="fa fa-heart icon-next-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">laudukang</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> 强力驱动 v4.2.0
  </div>
  <span class="post-meta-divider">|</span>
  <div class="theme-info">主题 – <a href="https://muse.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Muse</a> v7.7.1
  </div>

        
<div class="busuanzi-count">
  <script pjax async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
</div>






  <script pjax>
  function leancloudSelector(url) {
    url = encodeURI(url);
    return document.getElementById(url).querySelector('.leancloud-visitors-count');
  }
  if (CONFIG.page.isPost) {
    function addCount(Counter) {
      var visitors = document.querySelector('.leancloud_visitors');
      var url = decodeURI(visitors.getAttribute('id'));
      var title = visitors.getAttribute('data-flag-title');

      Counter('get', `/classes/Counter?where=${JSON.stringify({ url })}`)
        .then(response => response.json())
        .then(({ results }) => {
          if (results.length > 0) {
            var counter = results[0];
              leancloudSelector(url).innerText = counter.time + 1;
            Counter('put', '/classes/Counter/' + counter.objectId, { time: { '__op': 'Increment', 'amount': 1 } })
              .then(response => response.json())
              .catch(error => {
                console.error('Failed to save visitor count', error);
              })
          } else {
              Counter('post', '/classes/Counter', { title: title, url: url, time: 1 })
                .then(response => response.json())
                .then(() => {
                  leancloudSelector(url).innerText = 1;
                })
                .catch(error => {
                  console.error('Failed to create', error);
                });
          }
        })
        .catch(error => {
          console.error('LeanCloud Counter Error', error);
        });
    }
  } else {
    function showTime(Counter) {
      var visitors = document.querySelectorAll('.leancloud_visitors');
      var entries = [...visitors].map(element => {
        return decodeURI(element.getAttribute('id'));
      });

      Counter('get', `/classes/Counter?where=${JSON.stringify({ url: { '$in': entries } })}`)
        .then(response => response.json())
        .then(({ results }) => {
          if (results.length === 0) {
            document.querySelectorAll('.leancloud_visitors .leancloud-visitors-count').forEach(element => {
              element.innerText = 0;
            });
            return;
          }
          for (let item of results) {
            let { url, time } = item;
            leancloudSelector(url).innerText = time;
          }
          for (let url of entries) {
            var element = leancloudSelector(url);
            if (element.innerText == '') {
              element.innerText = 0;
            }
          }
        })
        .catch(error => {
          console.error('LeanCloud Counter Error', error);
        });
    }
  }

  fetch('https://app-router.leancloud.cn/2/route?appId=CPfRDhOlTyfkHW155W3Kx3H1-gzGzoHsz')
    .then(response => response.json())
    .then(({ api_server }) => {
      var Counter = (method, url, data) => {
        return fetch(`https://${api_server}/1.1${url}`, {
          method: method,
          headers: {
            'X-LC-Id': 'CPfRDhOlTyfkHW155W3Kx3H1-gzGzoHsz',
            'X-LC-Key': 'TX05RQSQMd8fbL7RaJNADS7S',
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(data)
        });
      };
      if (CONFIG.page.isPost) {
        if (CONFIG.hostname !== location.hostname) return;
        addCount(Counter);
      } else if (document.querySelectorAll('.post-title-link').length >= 1) {
        showTime(Counter);
      }
    });
  </script>


      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/pjax/pjax.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js"></script>
  <script src="//cdn.jsdelivr.net/gh/fancyapps/fancybox@3/dist/jquery.fancybox.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/muse.js"></script>


<script src="/js/next-boot.js"></script>

  <script>
var pjax = new Pjax({
  selectors: [
    'head title',
    '#page-configurations',
    '.content-wrap',
    '.post-toc-wrap',
    '#pjax'
  ],
  switches: {
    '.post-toc-wrap': Pjax.switches.innerHTML
  },
  analytics: false,
  cacheBust: false,
  scrollTo : !CONFIG.bookmark.enable
});

window.addEventListener('pjax:success', () => {
  document.querySelectorAll('script[pjax], script#page-configurations, #pjax script').forEach(element => {
    var code = element.text || element.textContent || element.innerHTML || '';
    var parent = element.parentNode;
    parent.removeChild(element);
    var script = document.createElement('script');
    if (element.id) {
      script.id = element.id;
    }
    if (element.className) {
      script.className = element.className;
    }
    if (element.type) {
      script.type = element.type;
    }
    if (element.src) {
      script.src = element.src;
      // Force synchronous loading of peripheral JS.
      script.async = false;
    }
    if (element.getAttribute('pjax') !== null) {
      script.setAttribute('pjax', '');
    }
    if (code !== '') {
      script.appendChild(document.createTextNode(code));
    }
    parent.appendChild(script);
  });
  NexT.boot.refresh();
  // Define Motion Sequence & Bootstrap Motion.
  if (CONFIG.motion.enable) {
    NexT.motion.integrator
      .init()
      .add(NexT.motion.middleWares.subMenu)
      .add(NexT.motion.middleWares.postList)
      .bootstrap();
  }
  NexT.utils.updateSidebarPosition();
});
</script>




  















    <div id="pjax">
  

  
<script>window.va = window.va || function () { (window.vaq = window.vaq || []).push(arguments); };</script><script defer src="/_vercel/insights/script.js" data-endpoint="/this-is-vercel-insights"></script><script>window.si = window.si || function () { (window.siq = window.siq || []).push(arguments); };</script><script defer src="/_vercel/speed-insights/script.js" data-endpoint="/this-is-vercel-insights-speed"></script>
    </div>
</body>
</html>
